package com.parktech.sun.domain.service.email.impl;

import com.parktech.sun.domain.model.email.EmailSubscription;
import com.parktech.sun.domain.repository.BaseRepository;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.repository.email.EmailRepository;
import com.parktech.sun.domain.service.email.EmailService;
import com.parktech.sun.domain.service.impl.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User: Think
 * Date: 11-1-28
 * Time: 上午3:28
 */
@Service
public class EmailServiceImpl extends BaseServiceImpl<EmailSubscription> implements EmailService {

    private EmailRepository emailRepository;

    @Autowired
    public EmailServiceImpl(EmailRepository emailRepository) {
        super(emailRepository);
        this.emailRepository = emailRepository;
    }

    public Page search(String emailLike, Page page) {

        Criteria criteria = emailRepository.createCriteria();

        if (StringUtils.isNotEmpty(emailLike)) {
            criteria.add(Property.forName("email").like(emailLike, MatchMode.ANYWHERE));
        }

        criteria.addOrder(Order.desc("modifyTime"));

        return emailRepository.page(criteria, page);

    }

    public EmailSubscription getByEmail(String email) {
        Criteria criteria = emailRepository.createCriteria();

        if (StringUtils.isNotEmpty(email)) {
            criteria.add(Property.forName("email").eq(email));
        }
        List list = criteria.list();
        if (list == null || list.size() == 0) {
            return null;
        }
        return (EmailSubscription) list.get(0);
    }
}
